import cgi
import urlparse
import wsgiref.handlers

from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

def getOpmServer():
    opmServers = []
    opmServers.append('http://rogerxu-opm.appspot.com/')
    opmServers.append('http://server4.operamini.com/')
    opmServers.append('http://demo.opera-mini.net:9002/')
    opmServers.append('http://google-cust.opera-mini.net/')
    opmServers.append('http://global-4-lvs-usa.opera-mini.net/')
    opmServers.append('http://p09-15.opera-mini.net/')
    opmServers.append('http://r01-15.opera-mini.net/')
    opmServers.append('http://r03-15.opera-mini.net/')

    return opmServers[0]

class MainPage(webapp.RequestHandler):

    opmServer = getOpmServer()

    def get(self):
        if self.request.get('test'):
            self.response.set_status(200)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write('This is Opera Mini Server Proxy!<br />\n')
            self.response.out.write('Current Server: %s' % (self.opmServer))
        else:
            self.response.set_status(301)
            self.response.headers['Location'] = 'http://www.google.com/ncr'

    def post(self):
        url = self.opmServer
        headers = {'Content-Type': 'application/xml'}
        result = urlfetch.fetch(url, payload=self.request.body, method=urlfetch.POST, headers=headers, deadline=30)
        self.response.set_status(result.status_code)
        self.response.headers['Content-Type'] = 'application/octet-stream'
        self.response.headers['Cache-Control'] = 'private, no-cache'
        self.response.out.write(result.content)

application = webapp.WSGIApplication([
    ('/', MainPage)
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
